//
//  NSObject+HDCityAreaDataManager.m
//  app
//
//  Created by D on 15/5/13.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDCityAreaDataManager.h"
#import "HDAreaModel.h"

@interface HDCityAreaDataManager ()

@property (nonatomic, retain) JKHttpClient * http;
@property (nonatomic, retain) JKHttpClient * httpTest;
@property (nonatomic, strong) SNUniteUrl * uniterUrl;

@property (nonatomic, retain) NSMutableArray * mutableArray;
@property (nonatomic,retain) FMDatabaseQueue * fmdbQueue;

@property (nonatomic, retain) NSData * myData;
@property (nonatomic, assign) BOOL includeCity;
@property (nonatomic, assign) BOOL includeData;
@property (nonatomic, strong) NSString * pid;

@end

@implementation HDCityAreaDataManager

+ (HDCityAreaDataManager *)shareManager
{
    AS_SINGLETON(HDCityAreaDataManager, manager, {
        manager = [[HDCityAreaDataManager alloc] init];
        manager.http = [[JKHttpClient alloc] init];
        manager.httpTest = [[JKHttpClient alloc] init];
        manager.mutableArray = [[NSMutableArray alloc] init];
        manager.uniterUrl = [SNUniteUrl shareUniteUrl];
        HDAppDelegate * delegate = (HDAppDelegate *)[UIApplication sharedApplication].delegate;
        manager.fmdbQueue = delegate.fmdbQueue;
    })
    return manager;
}
- (void)loadCityAreaData:(HDCityAreaHttpResult *)result WithPid:(NSString*)pid
{
    if ([self.http isRunning]) {
        return;
    }
    self.pid = pid;
    
    [self.httpTest get:self.uniterUrl.static_distinct_carrypageUrl params:[NSString stringWithFormat:@"%@",pid] result:^(JKResponse *resp) {
        
        if (resp.OK) {
            result.success = YES;
            
            result.dataArray = [self provinceDataSourceArrayWithArray:resp.content[@"result"] pid:pid];
        }else if (resp.failure){
            result.failure = YES;
        }
        [result invoke];
    }];
    
}
#pragma mark - 网络返回数据的处理
- (NSArray *)provinceDataSourceArrayWithArray:(NSArray *)array pid:(NSString*)pid
{
    //将刷新的时间保存起来
    NSDate * date = [NSDate date];
    NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:date forKey:@"provinceLastRefreshTime"];
    
    [self.mutableArray removeAllObjects];
    [self saveDataToDB:array PID:pid];
    
       for (NSDictionary * dict in array) {
           NSLog(@"dict = %@",dict);
       [self.mutableArray addObject:[HDAreaModel modelWithDict:dict]];
       }
    
    return self.mutableArray;
}

#pragma mark - 保存数据到数据库
- (void)saveDataToDB:(NSArray *)array  PID:(NSString*)pid
{
    //删除以前的数据表
    [self deleteCity:pid];
    
    [self createFmdb:pid];
    
    NSData * data = [NSKeyedArchiver archivedDataWithRootObject:array];
    
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"insert into City_%@ (Data) values(?);",pid];
        NSArray *arguments = @[data];
        
        if ([db executeUpdate:sql withArgumentsInArray:arguments]) {
            DLog(@"已经将City第一页的数据添加到了数据库");
        }
        //[db close];
    }];
    //[self.fmdbQueue close];
}

#pragma mark - 是否自动刷新数据
- (BOOL)shouldRefreshCityData:(NSString*)pid
{
    NSFileManager * fm = [NSFileManager defaultManager];
    
    if ([fm fileExistsAtPath:kDBPath]) {//数据库文件已经存在
        //判断表是不是存在:
        if ([self fmdbIncludeCity:pid]) {//表是存在的
            //通过时间判断是否需要自动刷新
            NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
            NSDate * cityLastRefreshTime = [ud objectForKey:@"cityLastRefreshTime"];
            NSDate * nowDate = [NSDate date];
            DLog(@"provinceLastRefreshTime ==== %@",cityLastRefreshTime);
            NSTimeInterval aTimer = [nowDate timeIntervalSinceDate:cityLastRefreshTime];
            DLog(@"City时间差  ===== %f",aTimer);
            if (aTimer > PROVINCEREFRESHSETIME) {//已经有一段时间没有刷新了,需要自动刷新
                DLog(@"City需要自动刷新");
                return YES;
            } else {//不需要自动刷新
                DLog(@"City不需要自动刷新");
                return NO;
            }
        } else {//表不存在,第一次进入此页面
            return YES;
        }
    } else {//数据库文件都不存在,第一次进入这个页面
        return YES;
    }
}

#pragma mark - 创建表
- (void)createFmdb:(NSString*)pid
{
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"create table if not exists City_%@(ID integer primary key autoincrement, Data blob);",pid];
        BOOL ret2 = [db executeUpdate:sql];
        if (ret2) {
            DLog(@"创建City表成功");
        }
        //[db close];
    }];
//    [self.fmdbQueue close];
}

#pragma mark - 从数据库中读取数据
- (NSArray *)arrayFromFmdb:(NSString*)pid
{
    self.myData = [NSData data];
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"select * from sqlite_master where name  = 'City_%@';",pid];
        if ([[db executeQuery:sql] next]){
            NSString * sql2 = [NSString stringWithFormat:@"select * from City_%@;",pid];
            FMResultSet * set = [db executeQuery:sql2];
            
            if ([set next]) {
                self.myData = [set dataForColumn:@"Data"];
            }
            
        }
//        [db close];
    }];
//    [self.fmdbQueue close];
    
    NSArray * array = [NSKeyedUnarchiver unarchiveObjectWithData:self.myData];
    [self.mutableArray removeAllObjects];
    for (NSDictionary * dict in array) {
        
        [self.mutableArray addObject:[HDAreaModel modelWithDict:dict]];
    }
    return self.mutableArray;
}

#pragma mark - 表是否存在
- (BOOL)fmdbIncludeCity:(NSString*)pid
{
    NSFileManager * fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:kDBPath]) {//数据库文件已经存在
        //判断表是不是存在:
        [self.fmdbQueue inDatabase:^(FMDatabase *db) {
            NSString * sql = [NSString stringWithFormat:@"select * from sqlite_master where name  = 'City_%@';",pid];
            if ([[db executeQuery:sql] next]) {//表是存在的
                DLog(@"City表存在");
                self.includeCity = YES;
            } else {//表不存在,第一次进入此页面
                DLog(@"City表不存在");
                self.includeCity = NO;
            }
//            [db close];
        }];
//        [self.fmdbQueue close];
    } else {//数据库文件都不存在,第一次进入这个页面
        self.includeCity = NO;
    }
    return self.includeCity;
}

#pragma mark - 表中是否存有数据
- (BOOL)fmdbIncludeData:(NSString*)pid
{
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"select * from sqlite_master where name  = 'City_%@';",pid];
        if ([[db executeQuery:sql] next]){
            NSString * sql2 = [NSString stringWithFormat:@"select * from City_%@;",pid];
            FMResultSet * set = [db executeQuery:sql2];
            
            if ([set next]) {
                DLog(@"City表格中数据是存在的");
                self.includeData =  YES;
            } else {
                DLog(@"City表格中数据不存在");
                self.includeData =  NO;
            }
            
        } else {
            self.includeData =  NO;
        }
//        [db close];
    }];
//    [self.fmdbQueue close];
    return self.includeData;
}

#pragma mark - 删除表
-(void)deleteCity:(NSString*)pid
{
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"select * from sqlite_master where name  = 'City_%@';",pid];
        if ([[db executeQuery:sql] next]) {
            //表是存在的
            [db close];
            [db open];
            NSString * sql2 = [NSString stringWithFormat:@"drop table City_%@;",pid];
            if ([db executeUpdate:sql2]) {
                DLog(@"City表格已经删除");
            }
        }
//        [db close];
    }];
//    [self.fmdbQueue close];
}

#pragma mark - cityURL 是否相同
-(BOOL)shouldRfreshCityData
{
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"cityUrl"] isEqualToString:self.uniterUrl.static_distinct_carrypageUrl ]) {
        
        [[NSUserDefaults standardUserDefaults]setObject:self.uniterUrl.static_distinct_carrypageUrl  forKey:@"cityUrl"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        return YES;
        
    }else
        return NO;
}

@end






